package com.jt.www.queue.issue;

import com.jt.www.admin.market.service.CommissionService;
import com.jt.www.domain.enums.common.YesOrNoEnum;
import com.jt.www.domain.po.CommissionPush;
import com.jt.www.domain.vo.IssueMessageVo;
import com.jt.www.util.JsonUtils;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 监听投保中心出单
 */
@Component
public class IssueListener {

    public static final Logger log = LoggerFactory.getLogger(IssueListener.class);

    @Autowired
    private CommissionService commissionService;

    @RabbitListener(queues = "${jtpf.rabbit.queuename.issue}")
    public void processMsg(Message msg, Channel channel) {
        String logId = "InsCommission_" + System.currentTimeMillis();
        log.info("{}:IssueListener get MessageProperties  {}", logId, msg.getMessageProperties().toString());
        log.info("{}:IssueListener get MessageBody  {}", logId, new String(msg.getBody()));
        byte[] msgBody = msg.getBody();
        if (msgBody == null || msgBody.length == 0) {
            log.info("{}:出单报文为空 {} {}", logId, msg.getMessageProperties().getReceivedExchange(), msg.getMessageProperties().getReceivedRoutingKey());
        } else {
            try {
                IssueMessageVo issueMessageVo = JsonUtils.fromJson(new String(msgBody), IssueMessageVo.class);
                if (YesOrNoEnum.yes(issueMessageVo.getIsuueType())) {
                    CommissionPush commissionPush = commissionService.createInsCommissionPush(logId, issueMessageVo.getApplicationFormCode());
                    if (null == commissionPush) {
                        log.info("{}:投保单号为: {} 的佣金不进行推送.", logId, issueMessageVo.getApplicationFormCode());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("{}:出单报文处理失败 {} {}", logId, msg.getMessageProperties().getReceivedExchange(), msg.getMessageProperties().getReceivedRoutingKey());
            }
        }
        basicAck(channel, msg.getMessageProperties().getDeliveryTag(), logId);

    }

    /**
     * ack确认
     *
     * @param channel
     * @param deliveryTag
     * @param logId
     */
    private void basicAck(Channel channel, long deliveryTag, String logId) {
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            log.error("{}:ACK确认出错，出错信息为", logId, e);
        }
    }

}
